·<template>
  <Container class="bargain-rules">
    <div class="container-header title title-center" slot="header">工厂特价</div>
    <div class="bg-light">
      <div class="container-title">
        <span>促销规则</span>
        <Button type="primary" @click="onJoinback" >修改促销</Button>
      </div>
      <Form :label-width="140" ref="form" >
        <Row>
          <Col span="8">
            <FormItem label="促销名称：">{{bargainName}}</FormItem>
            <FormItem label="活动标签：">{{bargainTag}}</FormItem>
            <FormItem label="参与经销商：">
              <span v-if="allDistributor">全部经销商</span> 
              <span v-else class="link" @click="onJoinDistribut">（参与详情）</span>
            </FormItem>
            <FormItem label="开启锁屏消息：">{{bargainAllRemind}}</FormItem>
          </Col>
          <Col span="8">
            <FormItem label="宣传语："><div class="e1">{{bargainGate}}</div></FormItem>
            <FormItem label="活动时间：">{{bargainDate[0] | dateTime}}- {{bargainDate[1] | dateTime}}</FormItem>
            <FormItem label="例外延时激活限时：">{{delayDate[0] | dateTime}}- {{delayDate[1] | dateTime}}</FormItem>
            <FormItem label="限购数量：" v-if="limitTypeEnum== 'STORE_TYPE'">{{stroeTypeList}}</FormItem>
            <FormItem label="通用门店限购数量：" v-else>{{$store.state.bargain.form.limitNum}}</FormItem>
            <FormItem label="例外门店限购数量：" v-if="barginIsStore">
              <!-- <ul>
                <li v-for="(item, index) of exceptionalStoreDTOList" :key="index">
                  {{item.storeName}}，限购：{{item.limitNum}}
                </li>
              </ul> -->
              <!-- <div>{{storeCount}}<span class="link" @click="showStoreList">（修改例外门店）</span></div> -->
              <div>{{$store.state.bargain.form.exceptionalCount}}</div>
            </FormItem>
            <FormItem label="例外经销商限购数量：" v-else>
              <div>{{$store.state.bargain.form.exceptionalCount}}</div>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="积分返利、优惠券激活限时：" label-width="180">{{bargainIntegralDate[0] | dateTime}}-{{bargainIntegralDate[1] | dateTime}}</FormItem>
            <FormItem label="手机号：" label-width="180" v-if="!bargainIsSet">{{$store.state.bargain.form.phoneList.map(item=> {return item.value}).join(',')}}</FormItem>
            <FormItem label="阈值：" label-width="180" v-if="!bargainIsSet">{{$store.state.bargain.form.warningQuantity}}</FormItem>
            <FormItem label-width="180" label="锁屏信息：" v-if="bargainAllRemind == '是'">{{bargainRemindList}}</FormItem>
          </Col>
        </Row>
      </Form>
    </div>
    <div class="bg-light mt choice-commidy">
      <div class="container-header">
        <SearchSale ref="search"  @onSearchData="onSearchData"></SearchSale>
      </div>
      <Tabs v-model="tab" @on-click="onChoiceTab">
        <Button class="item" type="primary"  slot="extra"  v-if="tab == 'tab2'" @click="onImportTemplate(0)">导入限制品牌商品</Button>
        <Button class="item" type="primary"  slot="extra"  v-if="tab == 'tab3'" @click="onImportTemplate(1)">导入非限制品牌商品</Button>
        <Button class="item" type="primary"  slot="extra" @click="onJoinAdd(1)" >加入限制品牌</Button>
        <Button class="item" type="primary"  slot="extra" @click="onJoinAdd(2)" >加入不限品牌</Button>
        <TabPane label="选择主商品" name="tab1" >
          <ChoiceCommidy ref="choice" @complete="onPrevertion"></ChoiceCommidy>
        </TabPane>
        <TabPane :label="label2" name="tab2">
          <LimitBrand ref="limit"></LimitBrand>
        </TabPane>
        <TabPane :label="label3" name="tab3">
          <UnLimitBrand ref="unLimit"></UnLimitBrand>
        </TabPane>
      </Tabs>
    </div>
    <Distributor ref="distributor"></Distributor>
    <SetCoupon ref="editCoupon" ></SetCoupon>
    <BatchSetIntegral ref="editIntegral"></BatchSetIntegral>
    <ImportTemplate ref="importTemplate" @completeUpload="getUploadData"></ImportTemplate>
    <!-- <storeList ref="storeEdit"></storeList> -->
    <ImportGoods ref="importGoods"/>
    <div class="container-footer bg-white" slot="footer">
      <Button size="large"  @click="jumpPrevPage">返回</Button>
      <Button type="primary" size="large" class="ml" :loading="loading" @click="onPrevertion()" v-if="isShelf == 'UNDER'">上架</Button>
      <Button type="primary" size="large" class="ml" @click="onJoinList">关闭</Button>
    </div>
    <Loader :status="status" @refresh="getData"></Loader>
  </Container>
</template>
<script>
import SearchSale from '@/views/sales/common/SearchSale'
import SetCoupon from './edit/BatchSetCouponItem'
import BatchSetIntegral from './edit/BatchSetIntegralItem'
import ImportTemplate from './edit/ImportTemplateItem'
import ImportGoods from './edit/ImportGoods' 
import Distributor from './edit/DistributorItem'
import ChoiceCommidy from './list/ChoiceCommidy'
import LimitBrand from './list/LimitBrands'
import UnLimitBrand from './list/UnLimitBrand'
// import storeList from './edit/StoreListItem'
import { mapGetters } from 'vuex'
import {formatDate, onSet} from '@/views/sales/common/TableSaleMethods'
export default {
  components: {
    SearchSale,
    SetCoupon,
    BatchSetIntegral,
    ImportTemplate,
    ChoiceCommidy,
    LimitBrand,
    UnLimitBrand,
    Distributor,
    ImportGoods,
    // storeList
  },
  data() {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      loading: false,
      tab: 'tab1',
      loading: false,
      status: 'pass',
      isShelf: 'ON',
      form: {
        tag: '',
        name: '',
        propagate: '',
        date: [],
        integralDate: [],
        currencyNum: '',
        num: '',
        isStoreType: ''
      },
      label2: (h) => {
        return h('div', [
          h('span', '限制品牌'),
          h('Badge', {
            props: {
              count: this.bargainLimiNum
            }
          }),
          h('Tooltip', {
            props: {
              content: '此区域内的商品只能被经营该品牌的门店看见',
              placement: "top-start",
              transfer: true
            }
          }, [h('Icon', {
            props: {
              type: "md-help-circle"
            },
            style: {
              marginLeft: '2px'
            }
          })])
        ]) 
      },
      label3: (h) => {
        return h('div', [
          h('span', '不限品牌'),
          h('Badge', {
            props: {
              count: this.bargainUnLimitNum
            }
          }),
          h('Tooltip', {
            props: {
              content: '此区域内的商品能被所有活动内的门店看见',
              placement: "top-start",
              transfer: true
            }
          }, [h('Icon', {
            props: {
              type: "md-help-circle"
            },
            style: {
              marginLeft: '2px'
            }
          })])
        ])
      }
    }
  },
  mounted() {
    this.$store.dispatch("getCouponsData")
    this.getDetailData()
    this.id && this.$store.dispatch("getShelfStatus", this.id).then(data => {
      this.isShelf = data
    })
  },
  methods: {
    getDetailData() {
      this.loading = true
      this.status = 'loading'
      this.$ajaxGet(`/activity/factory_info/detail/${this.id}`).then(data => {
        this.loading = false
        this.status = 'pass'
        this.$store.commit('getBargainDetail', data)
        this.loading = false
      }).catch(data => {
        this.loading = false
        this.status = 'error'
      })
    },
    onChoiceTab(e) {
      this.$refs.search.isShow = e
      this.$store.commit('setSetSearchEmpty')
      this.$refs.search.searchForm = {
        brandId: null,
        categoryId: null,
        keyword: "",
        code: "",
        skuCode: ""
      }
      if(this.$refs.search.isShow == 'tab1') {
        this.$refs.choice.getProductData({})
      } else if (this.$refs.search.isShow == 'tab2') {
        this.$refs.limit.getSkuPage({})
      } else if (this.$refs.search.isShow == 'tab3') {
        this.$refs.unLimit.getSkuPage({})
      }
    },
    getUploadData(data, type) {
      this.$refs.importGoods.openModal(data, type, this.id)
    },
    setItem(data, num) {
      for (let item of data) {
        for (let todo of item.productSkuList) {
          for(let type of num) {
            onSet(todo, item, type)
          }
        }
      }
    },
    onJoinAdd(type) {
      this.$refs.choice.getSaleData(type)
    },
    onPrevertion(type) {
      this.$jsonPost(`/activity/factory_info/shelf/${this.id}`).then((data) => {
        this.$Message.success("活动上架成功")
        this.$router.push({name: 'sales/list'})
      })
    },
    onJoinList() {
      this.$router.push({name: 'sales/list'})
    },
    onJoinback() {
      this.$router.back()
    },
    onSearchData (param) {
      this.$store.commit("onSetSearch", param)
      if(this.$refs.search.isShow == 'tab1') {
        this.$refs.choice.getProductData(param)
      } else if (this.$refs.search.isShow == 'tab2') {
        this.$refs.limit.getSkuPage(param)
      } else if (this.$refs.search.isShow == 'tab3') {
        this.$refs.unLimit.getSkuPage(param)
      }
    },
    onSetCoupon() {
      this.$refs.editCoupon.modal = true
    },
    onBatchSetThreshold() {
      this.$refs.editIntegral.reset({setType: 'threshold'})
    },
    onBatchSetIntegral() {
      this.$refs.editIntegral.reset({setType: 'integral'})
    },
    onBatchSetRebate() {
      this.$refs.editIntegral.reset({setType: 'rebate'})
    },
    onImportTemplate(type) {
      this.$refs.importTemplate.open(type)
    },
    onJoinDistribut() {
      this.$refs.distributor.modal = true
    },
    jumpPrevPage() {
      this.$router.back()
    },
    getLimit(data, param) {
        let newArray = [];
        for (let item of data) {
            for (let todo of item["productSkuList"]) {
              newArray.push({
                isLimitBrand: param, // false-不限制 true-限制
                productId: todo.productId,
                skuId: todo.id,
                productSn: todo.parentcode,
                skuSn: todo.code,
                sellOutQuantity: todo.sellOutQuantity, // 促销库存
                promotionPrice: todo.sale,
                activityFactoryGift:{"giftCouponId":todo.giftCouponId == '0' ? '' : todo.giftCouponId, "giftPoint":todo.giftPoint, "giftRebate": todo.giftRebate}
              })
            }
        }
        return newArray;
    },
    showStoreList() {
      this.$refs.storeEdit.setShowMotal()
    }
  },
  computed: {
    ...mapGetters([
      'bargainName',
      'bargainTag',
      'bargainGate',
      'bargainDate',
      'delayDate',
      'bargainIntegralDate',
      'bargainStoreNum',
      'stroeTypeList',
      'bargainLimiNum',
      'bargainUnLimitNum',
      'aFDList',
      'storeTypeLimitNumberDTOList',
      'allDistributor',
      'bargainIsSet',
      'getCouponsData',
      'bargainAllRemind',
      'bargainRemindList',
      'exceptionalStoreDTOList',
      'storeCount',
      'barginIsStore'
    ]),
    limitTypeEnum() {
      return this.$store.state.bargain.form.isCurrencyNum == '0' ? 'GENERAL_STORE' : 'STORE_TYPE' 
    },
    timeList() {
      return [{
        startDatetime: formatDate(this.$store.state.bargain.form.date[0], true),
        endDatetime: formatDate(this.$store.state.bargain.form.date[1],true)
      }];
    },
    activeLimit() {
      return [{
          startDatetime: formatDate(this.$store.state.bargain.form.integralDate[0],true),
          endDatetime: formatDate(this.$store.state.bargain.form.integralDate[1],true)
        }
      ];
    },
    productSkuList() {
      let limitData = this.getLimit(this.$store.state.bargain.getBgLmtData, true)
      let unLimitData = this.getLimit(this.$store.state.bargain.getBgUnLmtData, false)
      return [...limitData,...unLimitData]
    }
  }
}
</script>

